import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: MENG
 * Date: 2022-07-14
 * Time: 23:04
 */
public class BinaryTree {
    static class TreeNode{
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //这个二叉树的根节点
    //public TreeNode root;
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }
    // 前序遍历
    void preOrder(TreeNode root){
        if(root == null){
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

/*    //前序遍历 OJ题
    public List<Integer> preorderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<>();
        if(root == null){
            return ret;
        }
        ret.add(root.val);
        List<Integer> leftTree = preorderTraversal(root.left);
        ret.addAll(leftTree);
        List<Integer> rightTree = preorderTraversal(root.right);
        ret.addAll(rightTree);
        return ret;
    }*/
// 中序遍历
    void inOrder(TreeNode root){
        if(root == null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);

    }

    /*//中序遍历OJ
    public List<Integer> inorderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<>();
        if(root == null){
            return  ret;
        }
        List<Integer> leftTree = inorderTraversal(root.left);
        ret.addAll(leftTree);

        ret.add(root.val);

        List<Integer> rightTree = inorderTraversal(root.right);
        ret.addAll(rightTree);
        return  ret;

    }*/
    //后序遍历
    void postOrder(TreeNode root){
        if(root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");

    }
   /* //后序遍历OJ
    public List<Integer> postorderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<>();
        if(root == null){
            return null;
        }
        List<Integer> leftTree = postorderTraversal(root.left);
        ret.addAll(leftTree);
        List<Integer> rightTree = postorderTraversal(root.right);
        ret.addAll(rightTree);

        ret.add(root.val);
    }*/

    // 子问题思路  获取树中节点的个数
    int size(TreeNode root) {
        if(root == null){
            return 0;
        }
        return size(root.left) + size(root.right) + 1;
    }

    //遍历思路：只要遍历到了节点 就nodeSize ++
    public static int nodeSize;
    void size2(TreeNode root){
        if(root == null){
            return;
        }
        nodeSize++;
        size2(root.left);
        size2(root.right);
    }

    //子问题 获取叶子节点的个数
    int getLeafNodeCount(TreeNode root){
        if(root == null){
            return 0;
        }
        if(root.left == null && root.right == null){
            return 1;
        }
        return getLeafNodeCount(root.left) + getLeafNodeCount(root.right);

    }
    //遍历思路
    public static int leafSize;
    void getLeafNodeCount2(TreeNode root){
        if(root == null){
            return;
        }
        if(root.left == null && root.right == null){
            leafSize++;
        }
        getLeafNodeCount2(root.left);
        getLeafNodeCount2(root.right);
    }

    // 获取第K层节点的个数
    int getKLevelNodeCount(TreeNode root,int k){
        if(root == null){
            return 0;
        }
        if(k == 1){
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1) + getKLevelNodeCount(root.right,k-1);
    }
    // 获取二叉树的高度  时间复杂度：O(N)
    int getHeight(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return (leftHeight > rightHeight ? leftHeight+1 : rightHeight+1);
    }

    //重复计算的错误示范
    int getHeight1(TreeNode root) {
        if(root == null) return 0;
        return (getHeight1(root.left) > getHeight1(root.right) ?
                getHeight1(root.left)+1 : getHeight1(root.right)+1);
    }

    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, char val){
        if(root == null){
            return null;
        }
        //某个节点 == val，那就返回这个节点
        if(root.val == val){
            return root;
        }
        TreeNode ret1 = find(root.left,val);
        if(ret1 != null){
            return ret1;
        }
        TreeNode ret2 = find(root.right,val);
        if(ret2 != null){
            return ret2;
        }
        return null;

    }
    /*
     * OJ题
     * */

    //1. 检查两颗树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q){
        if(p == null && q != null || p != null && q == null){
            return false;
        }
        if(p == null && q == null){
            return true;
        }
        if(p.val != q.val){
            return false;
        }

        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);


    }
    //2.另一颗树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot){
        if(root == null){
            return false;
        }
        //判断是不是两颗相同的树，依靠上面的isSameTree方法
        if(isSameTree(root,subRoot)){
            return true;
        }
        if(isSubtree(root.left,subRoot)){
            return true;
        }
        if(isSubtree(root.right,subRoot)){
            return true;
        }
        return false;

    }
    //4. 判断一颗二叉树是否是平衡二叉树
    //第一种方法，时间复杂度是O(n²)
    public boolean isBalanced(TreeNode root){
        if(root == null){
            return false;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return Math.abs(leftHeight - rightHeight) <=1
                && isBalanced(root.left)
                && isBalanced(root.right);
    }
    //第二种方法，重写求高度的方法，加入判断平衡条件
    public int maxDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        if(leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight-rightHeight) <= 1){
            return Math.max(leftHeight,rightHeight)+1;
        }else{
            return -1;
        }
    }
    public boolean isBalanced2(TreeNode root){
        if(root == null){
            return false;
        }
        return maxDepth(root) >= 0;
    }

    //5. 对称二叉树
    public boolean isSymmetric(TreeNode root){
        if(root == null){
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
    private boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
        if(leftTree == null && rightTree != null || leftTree != null && rightTree == null){
            return false;
        }
        if(leftTree == null && rightTree == null){
            return true;
        }
        if(leftTree.val != rightTree.val){
            return false;
        }
        return isSymmetricChild(leftTree.left,rightTree.right) && isSymmetricChild(leftTree.right,rightTree.left);
    }
    //层序遍历
    void levelOrder(TreeNode root){
        if(root == null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");//打印队首元素
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
        System.out.println();
    }

   /* //7. 二叉树的分层遍历
    public List<List<Integer>> levelOrder2(TreeNode root){
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null){
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> row = new ArrayList<>();
            while(size > 0){
                TreeNode cur = queue.poll();
                size--;
                row.add(cur.val);
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            ret.add(row);
        }
        return ret;
    }*/
    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root){
        if(root == null){
            return true;
        }
        Queue<TreeNode> queue =new LinkedList<>();
        queue.offer(root);

        //queue永远不会为空，因为里面也会存放null，所以用cur为空来跳出while循环
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur != null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else{
                break;
            }
        }
        while(!queue.isEmpty()){
            TreeNode cur = queue.peek();
            if(cur != null){
                //不是满二叉树·
                return false;
            }else{
                queue.poll();
            }
        }
        return true;

    }

    //8. 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先
    //第一种方法，模拟搜索二叉树的方法
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
        if(root == null){
            return null;
        }
        if(root == q || root == q){
            return root;
        }
        TreeNode retLeft = lowestCommonAncestor(root.left,p,q);
        TreeNode retRight = lowestCommonAncestor(root.right,p,q);
        if(retLeft != null && retRight != null){
            return root;
        }else if(retLeft != null){
            return retLeft;
        }else{
            return retRight;
        }
    }


    //第二张方法，用两个栈

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || p == null || q == null) {
            return null;
        }
        //存储遍历到p的路径
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root,p,stack1);

        //存储遍历到q的路径
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,q,stack1);

        //元素多的，先出栈tmp个元素
        int size1 = stack1.size();
        int size2 = stack2.size();
        if(size1 > size2){
            int tmp = size1 - size2;
            while(tmp != 0){
                stack1.pop();
                tmp--;
            }
        }else{
            int tmp = size2 - size1;
            while(tmp != 0){
                stack2.pop();
                tmp--;
            }
        }
        //两个栈当中 元素的个数是一样的，一起出栈
        while(!stack1.empty() && !stack2.empty()){
            if(stack1.peek() == stack2.peek()){
                return stack1.peek();
            }else{
                stack1.pop();
                stack2.pop();
            }

        }
        //都没有找到栈顶元素相同的，没有公共祖先。
        return null;

    }
    //将正确路径存储到栈中
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if(root == null || node == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean retLeft = getPath(root.left,node,stack);
        if(retLeft){
            return true;
        }
        boolean retRight = getPath(root.right,node,stack);
        if(retRight) {
            return true;
        }
        stack.pop();
        return false;
    }


    //9. 二叉搜索树转换成排序双向链表,中序遍历
    public TreeNode prev = null;
    public void ConvertChild(TreeNode root) {
        if(root == null){
            return;
        }
        ConvertChild(root.left);
        System.out.println(root.val + " ");
        root.left = prev;
        if(prev != null){
            prev.right = root;
        }
        prev = root;
        ConvertChild(root.right);


    }
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null) return null;

        ConvertChild(pRootOfTree);

        TreeNode head = pRootOfTree;
        while(head.left != null) {
            head = head.left;
        }
        return head;
    }

   /* //10. 根据一棵树的前序遍历与中序遍历构造二叉树。
    public int preIndex = 0;
    private TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend) {
        if(inbegin > inend){
            return null;
        }
        //在前序遍历的数组中，找到每次的头结点，这里因为不是char类型的，会报错。
        TreeNode root =new TreeNode(preorder[preIndex]);
        int rootIndex =  findInorderIndex(inorder,preOrder(preIndex),inbegin,inend);
        preIndex++;

        //左树的ie的下标是ri下标-1，ib不变；右树是ib的下标ri下标+1，ie不变
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }

    //在中序遍历的数组中，找到前序遍历的根val，并返回下标。
    //inend就是最后一个元素的下标，所以不用-1
    private int findInorderIndex(int[] inorder,int val,int inbegin,int inend){
        for (int i = inbegin; i <=inend ; i++) {
            if(inorder[i] == val){
                return i;
            }

        }
        return -1;

    }*/

/*    //11.根据一棵树的中序遍历与后序遍历构造二叉树
    public int postIndex = 0;
    private TreeNode buildTreeChild(int[] postorder,int[] inorder,int inbegin,int inend){
        //没有了左树或者没有了右树
        if(inbegin > inend){
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = findInorderIndex(inorder,postorder[postIndex],inbegin,inend);
        postIndex --;

        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);
        root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);

        return root;

    }
    private int findInorderIndex(int[] inorder,int val,int inbegin,int inend){
        for (int i = inbegin; i <= inend ; i++) {
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        //从尾部向头开始遍历
        postIndex = postorder.length-1;
        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }*/

    //13. 二叉树前序非递归遍历实现
    public  void preorderTraversalNor(TreeNode root){
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur =root;

        while(cur != null || !stack.empty()){
            while(cur != null){
                stack.push(cur);
                System.out.println(cur.val + " ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = cur.right;
        }
    }
    //14. 二叉树中序非递归遍历实现
    public void inorderTraversal(TreeNode root){
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.empty()){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            System.out.println(top.val + " ");
            cur = cur.right;

        }
    }
    //15. 二叉树后序非递归遍历实现。
    public void postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;//记录已经打印过的节点。
        while(cur != null || !stack.empty()){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.peek();
            if(root.right == null || root.right == prev){
                stack.pop();
                //左树和右树都访问完了，在打印节点
                System.out.println(top.val + " ");
                //记录打印过的节点，给到prev；
                prev = top;
            }else{
                cur = cur.right;
            }
        }
    }



}
